package threaddemo;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(5, new MainTask());
        new SubTask("a", cb).start();
        new SubTask("b", cb).start();
        new SubTask("c", cb).start();
        new SubTask("d", cb).start();
        new SubTask("e", cb).start();
    }
}

class MainTask implements Runnable {

    @Override
    public void run() {



        System.out.println("...... 终于执行最后的任务了");
    }
}

class SubTask extends Thread {

    private String name;
    private CyclicBarrier cb;

    SubTask(String name, CyclicBarrier cb) {
        this.name = name;
        this.cb = cb;
    }

    @Override
    public void run() {
        System.out.println("[并发任务" + name + "]开始执行");


        try {
            Thread.sleep(30);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("[并发任务" + name + "]  开始执行完毕，通知障碍器");
        try {
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
